package service.impl;

import constants.EPlatform;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import service.SystemCommandService;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * linux系统的命令实现
 *
 * @author admin
 */
@Service
public class LinuxSystemCommandServiceImpl implements SystemCommandService {

    @Override
    public EPlatform getType() {
        return EPlatform.Linux;
    }

    @Override
    public Process excuteCMDCommand(String cmdCommand) {
        System.out.println("执行Linux命令：" + cmdCommand);
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(new String[]{"sh", "-c", cmdCommand});
            return process;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void killProcessTree(Process process, String rtspUrl) {
        process = null;
        String pid = getPid(rtspUrl);
        if (StringUtils.isEmpty(pid)) {
            System.out.println("未找到包含" + rtspUrl + "命令的pid");
            return;
        }
        BufferedReader reader = null;
        try {
            //杀掉进程
            process = Runtime.getRuntime().exec("kill -9 " + pid);
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println("kill PID return info -----> " + line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (process != null) {
                process.destroy();
            }

            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ignored) {

                }
            }
        }
    }

    private static String getPid(String command) {
        BufferedReader reader = null;
        try {
            //显示所有进程
            Process process = Runtime.getRuntime().exec("ps -ef");
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                if (line.contains(command)) {
                    System.out.println("相关信息 -----> " + command);
                    String[] strs = line.split("\\s+");
                    return strs[1];
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {

                }
            }
        }
        return null;
    }
}
